﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace SharpSoft.WPF.Validations
{
    /// <summary>
    /// 对枚举值进行验证
    /// </summary>
    public class EnumValidationRule : ValueValidationRule
    {
        public EnumValidationRule()
        {
            base.AllowNull = false;
            this.EnumError = this.NullError = "必须选择";

        }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var result = base.Validate(value, cultureInfo);
            if (result != Uncertainty)
            {
                return result;
            }
            var t = value.GetType();
            if (EnumType != null)
            {
                if (!EnumType.IsAssignableFrom(value.GetType()))
                {
                    return new ValidationResult(false, EnumError ?? "类型不匹配");
                }
            }
            if (!t.IsEnum)
            {
                return new ValidationResult(false, EnumError ?? "提供的值不是枚举");
            }
            var values = Enum.GetValues(t);
            foreach (var item in values)
            {

                if (item.Equals(value))
                {
                    return ValidationResult.ValidResult;
                }
            }
            return new ValidationResult(false, EnumError ?? "提供的值不在枚举范围内");
        }

        public Type EnumType { get; set; }

        public string EnumError { get; set; } = null;

    }
}
